﻿namespace Manhua2.SQLiteTable
{
    using HtmlAgilityPack;
    using Manhua2.Helper;
    using SQLite;
    using System;
    using System.IO;
    using System.Net;
    using System.Threading.Tasks;

    public static class InitializeDB
    {
        /// <summary>
        /// 开发时使用的代码， 创建缓存数据库
        /// </summary>
        public static void CreateDataBase()
        {
            SQLiteConnectionString connectionString = new SQLiteConnectionString("install.db", true);

            using (SQLiteConnection conn = new SQLiteConnection(connectionString.DatabasePath, connectionString.StoreDateTimeAsTicks))
            {
                conn.CreateTable<SQLiteComic>();
                conn.CreateTable<SQLiteChapter>();
                conn.CreateTable<SQLitePage>();
                conn.CreateTable<SQLiteHistory>();
                conn.CreateTable<SQLiteFavorite>();
            }            
        }

        //public async static Task GenerateComicCache()
        //{
        //    // http://s.acg.178.com/mh/index.php?c=category&m=doSearch&status=0&reader_group=0&zone=0&initial=all&type=0&p=1&callback=search.renderResult

        //    SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(
        //        System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "install.db"));
        //    conn.BeginTransaction();
        //    for (int i = 1; i < 300; i++)
        //    {
        //        HttpWebRequest request = (HttpWebRequest)
        //                HttpWebRequest.Create(Uri.EscapeUriString
        //        (string.Format("http://s.acg.178.com/mh/index.php?c=category&m=doSearch&status=0&reader_group=0&zone=0&initial=all&type=0&p={0}&callback=search.renderResult", i)));
        //        using (HttpWebResponse response =
        //                    (HttpWebResponse)await request.GetResponseAsync())
        //        using (Stream stream = response.GetResponseStream())
        //        using (StreamReader sr = new StreamReader(stream))
        //        {
        //            JsonArray ja;
        //            string input = sr.ReadToEnd();
        //            input = input.Replace("search.render({\"result\":", "");
        //            input = input.TrimEnd(';').TrimEnd(')');
        //            input = input.Substring(input.IndexOf('['));
        //            input = input.Remove(input.LastIndexOf(']') + 1);
        //            if (!JsonArray.TryParse(input, out ja))
        //                return;

        //            DateTime origin = new DateTime(1970, 1, 1);
        //            foreach (var item in ja)
        //            {
        //                JsonObject jo = item.GetObject();
        //                SQLiteComic book = new SQLiteComic();

        //                book.Title = jo["name"].GetString();
        //                book.Author = jo["author"].GetString();
        //                book.Token = jo["comic_url"].GetString().Trim('/');
        //                book.CoverUrl = jo["comic_cover"].GetString();
        //                book.Type = jo["type"].GetString();
        //                book.Provider = "acg178";

        //                //SaveFile(book.CoverUrl, book.Token);

        //                //book.CoverPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, book.Token + ".jpg");

        //                conn.Insert(book);
        //            }
        //        }
        //    }

        //    conn.Commit();
        //}

        public async static Task GenerateComicCache()
        {
            // http://comic.sfacg.com/Catalog/Default.aspx?PageIndex=90

                SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(
                    System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "install.db"));
                for (int i = 1; i <= 91; i++)
                {
                    var request = (HttpWebRequest)
                            HttpWebRequest.Create(Uri.EscapeUriString
                    (string.Format("http://comic.sfacg.com/Catalog/Default.aspx?PageIndex={0}", i)));
                    using (var response =
                                (HttpWebResponse)await request.GetResponseAsync())
                    using (var stream = response.GetResponseStream())
                    {
                        var doc = new HtmlDocument();
                        doc.Load(stream);

                        conn.BeginTransaction();

                        var list = HtmlHelper.GetElementByClass(doc.DocumentNode, "Comic_Pic_List");
                        foreach (var ul in list)
                        {
                            SQLiteComic book = new SQLiteComic();
                            book.ChapterUrl = "http://comic.sfacg.com" +
                                              ul.ChildNodes[1].ChildNodes[1].Attributes["href"].Value;
                            book.CoverUrl = ul.ChildNodes[1].ChildNodes[1].ChildNodes[0].Attributes["src"].Value;
                            book.Title = ul.ChildNodes[1].ChildNodes[1].ChildNodes[0].Attributes["alt"].Value;
                            var links = HtmlHelper.GetElementByClass(ul, "Blue_link1");
                            book.Author = links[0].InnerText;
                            book.Type = links[1].InnerText;
                            book.Provider = "sfacg";
                            conn.Insert(book);
                        }

                        conn.Commit();
                    }
                }
 
        }

        public async static Task GenerateComicCacheForBenGou()
        {
            // http://www.bengou.com/all/index.html?p=1

            SQLite.SQLiteConnection conn = new SQLite.SQLiteConnection(
                System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "install.db"));
            for (int i = 1; i <= 308; i++)
            {
                int tries = 3;
                while (--tries > 0)
                {
                    try
                    {
                        var request = (HttpWebRequest)
                                HttpWebRequest.Create(Uri.EscapeUriString
                        (string.Format("http://www.bengou.com/all/index.html?p={0}", i)));
                        using (var response =
                                    (HttpWebResponse)await request.GetResponseAsync())
                        using (var stream = response.GetResponseStream())
                        {
                            var doc = new HtmlDocument();
                            doc.Load(stream);

                            conn.BeginTransaction();

                            var ul = doc.GetElementbyId("sa-comic_show_list").Element("ul");
                            var lis = ul.Elements("li");
                            foreach (var li in lis)
                            {
                                SQLiteComic comic = new SQLiteComic();

                                // 读取封面
                                var div = li.Element("div");
                                var link = div.Element("a");

                                comic.Title = link.Attributes["title"].Value.Trim();
                                comic.ChapterUrl = link.Attributes["href"].Value;

                                var cover = link.Element("img");

                                comic.CoverUrl = cover.Attributes["src"].Value;
                                comic.Provider = "bengou";

                                conn.Insert(comic);
                            }

                            conn.Commit();
                            tries = 0;
                        }
                    }
                    catch
                    {
                        conn.Rollback();
                    }
                }
            }


        }

        private async static void SaveFile(string url, string filename)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.CreateHttp(url);
            using (var response = await request.GetResponseAsync())
            {
                byte[] buffer = new byte[4096];
                int len;

                var file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync(filename);

                using(var ms = await file.OpenStreamForWriteAsync())
                using (var stream = response.GetResponseStream())
                {
                    while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, len);
                    }               
                }
            }
        }
    }
}
